package com.acme.service.bank.impl;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import com.acme.domain.account.Account;
import com.acme.domain.bank.Bank;
import com.acme.domain.bank.Client;
import com.acme.domain.bank.Gender;
import com.acme.exceptions.ClientExistsException;
import com.acme.service.bank.BankService;

public class BankServiceImpl implements BankService {
	public void saveBank(final Bank bank, final String pathTo)
			throws IOException {
		
		FileOutputStream fos = new FileOutputStream(pathTo);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(bank); 
		oos.close();
		fos.close();
	}

	public Bank loadBank(final String pathFrom) throws IOException {
		FileInputStream fis = new FileInputStream (pathFrom);
		ObjectInputStream ois = new ObjectInputStream(fis); 
		Bank bank = null;
		try {
			bank = (Bank)ois.readObject();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} 
		ois.close();
		fis.close();
		return bank;
	}
	
	public double getAccountBalance(Bank bank, int accountId) {
		ArrayList<Client> bankClients = bank.getClients();
		for(Client client: bankClients) {
			ArrayList<Account> clientAccounts = client.getAccounts();
			for(Account acc: clientAccounts) {
				if(acc.getAccountNumber() == accountId) {
					return acc.getBalance();
				}
			}
		}
		return -1;
	}

	@Override
	public Client addClient(Bank bank, String name, Gender gender) {
		Client client = new Client(name, gender);
		try {
			bank.addClient(client);
		} catch (ClientExistsException e) {
			e.printStackTrace();
		}
		return client;
	}
}